package org.jeecg.config.sign.util;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.filter.StringUtilFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;

/**
 * 保存过滤器里面的流
 * 
 * @author jeecg
 * @date 20210621
 */
@Slf4j
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    private ServletInputStream oriStream;

    private  String sessionString;

    public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        sessionString = getBodyString(request);
        //log.info("BodyReaderHttpServletRequestWrapper==========sessionString:"+sessionString);
        body = sessionString.getBytes(Charset.forName("UTF-8"));
        try {
            oriStream = getOriInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取请求Body
     *
     * @param request
     * @return
     */
    public String getBodyString(final ServletRequest request) {

        StringBuilder sb = new StringBuilder();
        try (InputStream inputStream = cloneInputStream(request.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")))) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * Description: 复制输入流</br>
     *
     * @param inputStream
     * @return</br>
     */
    public InputStream cloneInputStream(ServletInputStream inputStream) {

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buffer)) > -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            byteArrayOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    }

    @Override
    public BufferedReader getReader() throws IOException {

        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    /**
     * 字符串去除emoji的方法
     */
    private String convertEmoji2Str(String source) {
//        if(EmojiManager.containsEmoji(source)){
//            log.info("convertEmoji2Str==========source:"+source);
//            s= EmojiParser.removeAllEmojis(source);
//            log.info("BodyReaderHttpServletRequestWrapper==========s:"+s);
//        }
        source = StringUtilFilter.filterEmoji(source);
        source = StringUtilFilter.filterEmoji2(source);
        return source;
    }


    /**
     * 重写getInputStream方法 post请求参数必须通过流才能获取到值
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {

        String json = "{}";
        try {
            // 非json类型，直接返回
            if (!super.getHeader(HttpHeaders.CONTENT_TYPE).contains(MediaType.APPLICATION_JSON_VALUE) ) {
                log.info("BodyReaderHttpServletRequestWrapper==========非json类型，直接返回 ");
                return oriStream;
            }
            // 转化成字符串
            json = sessionString;

            if (oConvertUtils.isEmpty(json)) {
                return oriStream;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //去除表情并返回
        String noEmojiStr = convertEmoji2Str(json);

        // 写回request
        ByteArrayInputStream bais = new ByteArrayInputStream(noEmojiStr.getBytes("UTF-8"));

        return new ServletInputStream() {

            @Override
            public int read() {

                return bais.read();
            }

            @Override
            public boolean isFinished() {

                return false;
            }

            @Override
            public boolean isReady() {

                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }

    private ServletInputStream getOriInputStream() throws IOException {

        final ByteArrayInputStream bais = new ByteArrayInputStream(body);

        return new ServletInputStream() {

            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }
}